package com.walkingfiles

import com.walkingfiles.registry.Document
import com.walkingfiles.extjs.ExtJSConverter
import com.walkingfiles.alfresco.Utils

import grails.plugin.springsecurity.annotation.Secured

@Secured(['ROLE_USER'])
class AlfrescoController {

    def index() {
        
        def absolutePath = params.documentRoot
        if (!absolutePath) {
            absolutePath = grailsApplication.config.alfresco.rootPath
        }
        def recursive = params.recursive && params.recursive == 'yes'
        def includeDocuments = params.includeDocuments && params.includeDocuments == 'yes'
        def client = new Utils(grailsApplication.config.alfresco).getClient()
        def children = client.getContent(absolutePath, recursive)
        def root = new ExtJSConverter().contentToTree(children, 
                                                      includeDocuments)
        root['expanded'] = true
        render(contentType: 'application/json') {[
            children: root,
            success: true
        ]}
    }

    def getDocument() {
        def url = params.url.replaceAll(' ', '%20')
        def client = new Utils(grailsApplication.config.alfresco).getClient()
        def docResponse = client.get(url)
        def status = docResponse.getStatusLine().getStatusCode()
        def httpEntity = docResponse.getEntity()
        def contentType = httpEntity.getContentType().toString()
        def content = httpEntity.getContent()
        response.setHeader('Content-Type', contentType)
        response.outputStream << content
        content.close()        
    }

}
